package com.qf.config;

import com.qf.common.vo.MemberVo;
import com.qf.entity.Member;
import com.qf.service.MemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;

/**
 * @author KING
 * @ClassName: com.qf.config.shiro.MemberRealm
 * @Description: 该类的功能描述
 * @date: 2021/10/26 11:01
 */

public class MemberRealm extends AuthorizingRealm {
    @Resource
    private MemberService memberService;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //拿到的对象只有用户名
        String principal = (String) token.getPrincipal();
        //根据用户名去数据库查询，查询完要转换成vo对象
        Member member = memberService.login(principal);
        if (member == null) {
            throw new UnknownAccountException("账户或者密码不存在");
        }
        /**
         * Object principal,  从数据库中获取的认证对象
         * Object hashedCredentials,加密密码
         * ByteSource credentialsSalt,加密盐
         * String realmName 用户输入的用户名
         */
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties(member, memberVo);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(memberVo, member.getPassword(), ByteSource.Util.bytes(member.getSalt()), memberVo.getUsername());
        return simpleAuthenticationInfo;
    }
}
